<template>
   <div>
       <!-- 面包屑导航 -->
     <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
     </el-breadcrumb>
     <!-- 卡片栏 -->
     <el-card class="box-card">
        <div>
            <!-- 栅格系统划分等分 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList"> 
                        <el-button el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
        </div>
        <!-- 添加用户对话框区域 -->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeDialog">
            <!-- 主题区域 -->
           <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="ruleForm.username"></el-input>
                </el-form-item>
                 <el-form-item label="密码" prop="password">
                    <el-input v-model="ruleForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="ruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="ruleForm.mobile"></el-input>
                </el-form-item>
           </el-form>    
            <!-- 尾部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户对话框区域 -->
        <el-dialog title="修改用户" :visible.sync="editlogVisible" width="50%" @close="edutCloes">
            <!-- 主题区域 -->
           <el-form :model="resData" :rules="rules" ref="editRef" label-width="100px">
                <el-form-item label="用户名">
                    <el-input v-model="resData.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="resData.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="resData.mobile"></el-input>
                </el-form-item>
           </el-form>    
            <!-- 尾部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editlogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editSumbit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限对话框区域 -->
        <el-dialog title="分配权限" :visible.sync="rolesVisible" width="50%" @close="setRolesClose">
            <div>
                <p>当前的用户：{{userInfo.username}}</p>
                <p>当前的角色：{{userInfo.role_name}}</p>
                <p>分配新角色:
                     <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option v-for="item in roleList" :key="item.id"
                         :label="item.roleName"
                         :value="item.id">
                        </el-option>
                     </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rolesVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 表单区域 -->
        <template>
            <el-table :data="userlist" style="width: 100%" border stripe>
              <el-table-column type="index"></el-table-column>
              <el-table-column prop="username" label="姓名" width="180"></el-table-column>
              <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
              <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
              <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
              <!-- 布尔值无法显示到界面 -->
              <el-table-column  label="状态" width="180">
                  <!-- 作用域插槽 可以通过scope.row接收这一行的数据 -->
                  <template slot-scope="scope">
                      <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="changeSwitch(scope.row)"></el-switch>
                  </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                  <template slot-scope="scope"> 
                    <!-- 修改用户 -->
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="editForm(scope.row.id)"></el-button>
                     <!-- 删除用户 -->
                     <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
                     <!-- 分配角色 -->
                     <el-tooltip effect="dark" content="分配角色" placement="top-end" :enterable="false">
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="rolesFrom(scope.row)"></el-button>
                     </el-tooltip>   
                  </template>
              </el-table-column>
            </el-table>
        </template>      
        <!-- 分页区域 -->
        <div class="block">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1,2 , 4, 5]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </div>
    </el-card>
    </div>
</template>

<script>
export default {
    data () {
        var checkEmail=(rule, value, callback)=>{
             var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
             if(reg.test(value)){
               callback();
             }
             else callback(new Error('请输入合法邮箱'));
           }
        var checkMobile=(rule, value, callback)=>{
             var reg=/^1[3|4|5|7|8][0-9]{9}$/;
             if(reg.test(value)) {
               callback();
             }
             else callback(new Error('请输入正确手机号'));
           }
        return {
            queryInfo:{
                query:'',
                pagenum:1,
                pagesize:2
            },
            userlist:[],
            total:0,
            // 角色列表信息
            roleList:[],
            // 分配角色对话框默认情况
            rolesVisible:false,
            // 添加用户对话框默认情况
            dialogVisible: false,
            // 修改用户对话框默认情况
            editlogVisible:false,
            // 需要被分配角色的信息
            userInfo:{},
            // 根据id查询返回的数据
            resData:{},
            // 添加表单数据
            ruleForm: {
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            // 选中后的值
            selectedRoleId:'',
            // 添加表单验证规则
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                      { validator: checkEmail, trigger: 'blur' }
                    
                ],
                mobile: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                    
                ],
            }
        }
    },
    created () {
        this.getUsersList();
    },
    methods: {
        // 查询列表数据
        getUsersList: async function () {
            var {data:res}=await this.$http.get('users',
            {params:this.queryInfo});
            if(res.meta.status!=200){
                return this.$message.error(res.meta.msg);
            } 
            this.userlist=res.data.users;
            this.total=res.data.total;
            
        },
        // 当用户点击一页多少条数据触发
        handleSizeChange: function(val) {
            this.queryInfo.pagesize=val;
            this.getUsersList();

        },
        // 当用户点第几页触发
        handleCurrentChange(val) {
          this.queryInfo.pagenum=val;
          this,this.getUsersList();

        },
        // 当用户修改状态后 实现前后端数据同步
        changeSwitch: async function (val) {
          var {data:res}=await this.$http.put('users/'+val.id+'/state/'+val.mg_state);
          if(res.meta.status!=200) {
              val.mg_state!=val.mg_state;
              return this.$message.error('用户更新状态失败');
          }
          this.$message.success('更新用户状态成功');
        },
        // 当用户点击关闭对话框时候重置内容
        closeDialog() {
            this.$refs.ruleForm.resetFields();
        },
        edutCloes() {
            this.$refs.editRef.resetFields();
        },

        // 用户点击提交按钮 实现预验证和提交数据
        addUser() {
            this.$refs.ruleForm.validate(async(valid)=>{
                if(valid) {
                  var {data:res}=await this.$http.post('users',this.ruleForm);
                  if(res.meta.status==201) {
                      this.$message.success(res.meta.msg);
                      this.getUsersList();
                      this.dialogVisible=false;
                  }
                  else {
                      this.$message.error(res.meta.msg);
                      this.dialogVisible=false;
                  }  
                }
                else {
                    this.$message.error('数据提交有误');
                    this.dialogVisible=false;
                    return false;
                }
            })
        },
        // 用户点击修改 根据id向服务器查询数据
        async editForm(val) {
            var {data:res}=await this.$http.get('users/'+val);
            console.log(res);
            this.editlogVisible=true;
            if(res.meta.status==200) {
                this.resData=res.data;
                this.$message.success(res.meta.msg);
            }
            else{
                this.$message.error(res.meta.msg);
            }
        },
        // 点击修改提交操作 修改个人用户信息
        editSumbit() {
            this.$refs.editRef.validate(async(valid)=>{
                if(valid){
                    var {data:res}=await this.$http.put('users/'+this.resData.id,{
                        email:this.resData.email,
                        mobile:this.resData.mobile
                    });
                    if(res.meta.status==200) {
                        this.$message.success(res.meta.msg);
                    }
                    else{
                        this.$message.error(res.meta.msg);
                    } 
                    console.log(res);
                    this.getUsersList();
                    this.editlogVisible=false;
                }
                else {
                    this.$message.error('用户修改失败');
                    return false;
                }
            })   
        },
        // 删除个人用户
        deleteUser(val) {
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async() => {
                var {data:res}=await this.$http.delete('users/'+val);
                if(res.meta.status==200) {
                    this.getUsersList();
                    this.$message({    
                    type: 'success',
                    message: '删除成功!'
                    });
                }else {
                    this.$message.error(res.meta.msg);
                }
               
            }).catch(() => {
                this.$message({
                type: 'info',
                message: '已取消删除'
                });          
            });
            
        },
        // 点击分配权限按钮弹出数据
        async rolesFrom(val) {
            this.userInfo=val;
            // 获取角色列表信息
            var {data:res}=await this.$http.get('roles')
            if(res.meta.status==200) {
                this.roleList=res.data;
            }
            this.rolesVisible=true;
        },
        //点击按钮分配角色
        async saveRoleInfo() {
            if(!this.selectedRoleId) {
                this.$message.error('请选择要分配的角色');
            }
            var {data:res}=await this.$http.put('users/'+this.userInfo.id+'/role',{
                rid:this.selectedRoleId
            });
            if(res.meta.status==200) {
                this.$message.success(res.meta.msg);
                this.getUsersList();
            }
            else {
                this.$message.error(res.meta.msg);
            }
            this.rolesVisible=false;

        },
        // 监听分配角色对话框的关闭事件
        setRolesClose() {
            this.selectedRoleId='';
        }
    }
}
</script>

<style lang="less" scoped>
 .el-table {
     margin-top: 15px;
 }
 .block {
     margin-top: 15px;
 }
</style>